package top.lethelh.socket;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;

/**
 * @author lh
 * @date 2021/11/24 9:19 下午
 * @desc UDP 服务端
 */
public class UDPServer {
    public static void main(String[] args) {
        try (DatagramSocket socket = new DatagramSocket(65001)) {
            byte[] buff = new byte[100];
            DatagramPacket packet = new DatagramPacket(buff, buff.length);

            socket.receive(packet);

            byte[] data = packet.getData();
            String text = new String(data, 0, packet.getLength());
            System.out.println(text);
            byte[] sendContent = String.valueOf(text.length()).getBytes(StandardCharsets.UTF_8);
            DatagramPacket packetToClient = new DatagramPacket(sendContent, sendContent.length, packet.getAddress(), packet.getPort());

            socket.send(packetToClient);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
